using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.AcmsControls
{
    public class AcmsHttpModule : System.Web.IHttpModule    
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(System.Web.HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            System.Web.HttpApplication app = sender as System.Web.HttpApplication;
            if (app != null)
            {
                if ((app.Context.Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith("/default.aspx") || !System.IO.File.Exists(app.Context.Server.MapPath(app.Context.Request.Path))) && !app.Context.Request.Path.EndsWith(".axd"))
                {
                    string path = app.Context.Request.AppRelativeCurrentExecutionFilePath;
                    if (path.ToLower().EndsWith("/default.aspx"))
                    {
                        path = path.Remove(path.ToLower().IndexOf("/default.aspx"));
                    }
                    else
                    {
                        path = path.Remove(path.LastIndexOf("."));
                    }

                    //get template file to use
                    string templateName = app.Context.Request.QueryString["TF"];

                    //work out version to use default to current version ie date time now
                    DateTime versionTime = DateTime.Now;
                    if (app.Context.Request.QueryString["V"] != null)
                    {
                        try
                        {
                            //if time stamp uise that
                            versionTime = DateTime.Parse(app.Context.Request.QueryString["V"]);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                //if bool use that for pending id datetimeminium
                                bool pending = bool.Parse(app.Context.Request.QueryString["V"]);
                                if (pending)
                                {
                                    versionTime = DateTime.MinValue;
                                }
                            }
                            catch(FormatException)
                            {
                            }
                        }
                    }


                    string postKey = string.Concat(path, "_", templateName, "_", versionTime.ToString("yyyyMMddhhmm"));
                    string postQueryString = null;
                    //try ToString get from cache
                    if (app.Context.Cache[postKey] != null && app.Context.Cache[postKey] is string)
                    {
                        postQueryString = (string)app.Context.Cache[postKey];
                    }
                    //if not from db
                    if (string.IsNullOrEmpty(postQueryString))
                    {
                        string siteRoot = app.Context.Request.ServerVariables["Server_Name"];
                        if (app.Context.Request.ApplicationPath != "/")
                            siteRoot += app.Context.Request.ApplicationPath;
                        Acms.Bll.Post post = Acms.Bll.Post.GetBySiteUrlPostUrlAndVersionTimeStamp(siteRoot, path, versionTime);
                        if (post != null)
                        {
                            if (!string.IsNullOrEmpty(templateName))
                            {
                                if (post.GetFile(templateName) == null)
                                {
                                    throw new Acms.Exceptions.TemplateException(string.Format("Could not load template file '{0}' for post '{1}' template '{2}'", templateName, post.Path, post.TemplateName));
                                }
                                else
                                {
                                    postQueryString = post.GetQueryString(templateName, versionTime);
                                }
                            }
                            else
                            {
                                if (post.GetDefaultFile() == null)
                                {
                                    throw new Acms.Exceptions.TemplateException(string.Format("Could not load template file '{0}' for post '{1}' template '{2}'", templateName, post.Path, post.TemplateName));
                                }
                                else
                                {
                                    postQueryString = post.GetDefaultQueryString(versionTime);
                                }
                            }
                            app.Context.Cache.Insert(postKey, postQueryString, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                        }
                        else
                        {
                            throw new Exception(string.Format("Could not find '{0} '{1}'", siteRoot, path));
                        }
                    }

                    if (!string.IsNullOrEmpty(postQueryString))
                    {
                        if (app.Context.Request.QueryString.Keys.Count > 0)
                        {
                            postQueryString = string.Concat(postQueryString, "&", app.Context.Request.QueryString.ToString());
                        }
                        app.Context.RewritePath("~/LoadTemplate.aspx", null, postQueryString, false);
                    }
                }
            }
        }

        #endregion
    }
}
